package com.ha7419x.controller;

import com.ha7419x.vo.Dept;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class ConsumerDeptController {
    private static final String DEPT_GET_URL = "http://DEMO-PROVIDER-DEPT/dept/get/";
    private static final String DEPT_LIST_URL = "http://DEMO-PROVIDER-DEPT/dept/list";
    private static final String DEPT_ADD_URL = "http://DEMO-PROVIDER-DEPT/dept/add";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private HttpHeaders httpHeaders;
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping(value = "consumer/dept/get/{id}", method = RequestMethod.GET)
    public Object getDept(@PathVariable("id") Long id){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("DEMO-PROVIDER-DEPT");
        System.out.println(
                "【*** serviceInstance ***】 host = " + serviceInstance.getHost()
                    + "、port = " + serviceInstance.getPort()
                    + "、serviceId = " + serviceInstance.getServiceId());
        //加密访问
        Dept dept = this.restTemplate.exchange(DEPT_GET_URL + id, HttpMethod.GET
                , new HttpEntity<>(this.httpHeaders), Dept.class).getBody();
        //未加密访问
        //Dept dept = this.restTemplate.getForObject(DEPT_GET_URL + id, Dept.class);
        return dept;
    }

    @RequestMapping(value = "consumer/dept/list", method = RequestMethod.GET)
    public Object list(){
        //加密访问
        List<Dept> deptList = this.restTemplate.exchange(DEPT_LIST_URL, HttpMethod.GET
                , new HttpEntity<>(this.httpHeaders), List.class).getBody();
        //未加密访问
        //List<Dept> deptList = this.restTemplate.getForObject(DEPT_LIST_URL, List.class);
        return deptList;
    }

    @RequestMapping(value = "consumer/dept/add", method = RequestMethod.GET)
    public Object addDept(@RequestParam("deptName") String deptName){
        Dept dept = new Dept();
        dept.setDeptName(deptName);
        //加密访问
        boolean flag = this.restTemplate.exchange(DEPT_ADD_URL, HttpMethod.POST
                , new HttpEntity<>(dept, this.httpHeaders), Boolean.class).getBody();
        //未加密访问
        //boolean flag = this.restTemplate.postForObject(DEPT_ADD_URL, dept, Boolean.class);
        return flag;
    }
}
